import 'dart:math';

import 'package:flutter_uxin/Compontents/http_Dio/http_manager.dart';
import 'package:flutter_uxin/Compontents/http_Dio/address.dart';
import 'package:flutter_uxin/Compontents/http_Dio/result_data.dart';
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter_uxin/Tools/Define/Device.dart';
import 'package:flutter_uxin/Tools/config/commonTool.dart';

import 'package:flutter_uxin/Login/Parsers/LoginProfile.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'package:flutter_uxin/addressBook/Parsers/commonAddressBook.dart';

import 'package:flutter_uxin/Compontents/DB/DBManager.dart';
import 'dart:async';

class addressBookManager {
  // 工厂模式
  factory addressBookManager() => _instance;
  static addressBookManager get instance => getInstance();
  static addressBookManager _instance;

  ///通用全局单例，第一次使用时初始化
  addressBookManager._internal() {
    // 初始化
  }

  static addressBookManager getInstance() {
    if (_instance == null) {
      _instance = new addressBookManager._internal();
    }
    return _instance;
  }

  void tryUpdateAddress() async {
//     tryGetUserProfile();
//    String userType = await commonTool.getPreferencesValue('profile_user_type');
//    print('userType------------$userType');
//    int userType_Num = int.parse('$userType');

//    Future futureTest = new Future(() => print('开始'));
//    futureTest.then((_){
//
//    }).whenComplete((){
//      futureTest.then((_){
//
//      });
//    });

//    Future future = new Future(() => tryGetUserProfile());//获取个人信息
//    future.then((_) {
//      if (userType_Num == 3) {//获取教师通讯录
//        //老师
//        tryGetGroupsForTeacher();
//      } else {//获取家长通讯录
//        tryGetGroupsForParent();
//      }
//    }).then((_){//获取群组列表
//      tryGetJoinedGroups();
//    }).then((_){
//      if (userType_Num == 3) {
//        tryGetAllUserProfile();
//      }else{
//        updateAddressBookSucceed();
//
//      }
//
//    }).then((_){
//      if (userType_Num == 3) {
//        updateAddressBookSucceed();
//      }
//    });

    tryGetUserProfile().then((data) {
      beginUpdateAddress().then((_){tryGetJoinedGroups();});
    }).catchError((eer) {
      print('error--------tryGetUserProfile--------------$eer');
    });
  }

  /***********************通讯录更新
   *  学生 家长
   * 获取自身的详细信息->获取家长通讯录(清空数据库)->获取群组列表 -> 通讯录更新成功 ->更改更新标示
   *
   * 教师
   *获取自身的详细信息->获取教师通讯录(清空数据库)->获取群组列表 ->获取公共通讯录 ->通讯录更新成功 ->更改更新标示
   *
   * **************************************************************************/

  //获取自身的详细信息
  Future tryGetUserProfile() async {
    Completer completer = new Completer();

    String device_type = Device.getDevice_type();
    String deviceID = await Device.deviceID();
    String currentTime = Device.currentTimeMillis().toString();
    String user_name = await commonTool.getPreferencesValue('profile_name');
    var userProfile_url = await Address.url_get_userProfile;
    ResultData res = await HttpManager.getInstance().post(
        userProfile_url,
        {
          'user_name': '$user_name',
          'device_type': '$device_type',
          'device_identifier': '$deviceID',
          'time': '$currentTime',
        },
        responseType: ResponseType.plain);

    print('res.data-----tryGetUserProfile-----------------${res.data}');
    if (res.isSuccess) {
      String str = res.data;
//        print('url_get_RelationAccount--------responseJson--------------$str');
      Map responseJson = jsonDecode(str);

      Map errorMap = responseJson['error'];
      if (errorMap != null && errorMap is Map && errorMap.isNotEmpty == true) {
        String code = errorMap['code'];
        String message = errorMap['message'];
        completer.completeError('message');
        print('error--------tryGetUserProfile--------------$message');
      } else {
        LoginProfile user = new LoginProfile.fromJson(responseJson);
        saveProfile(user.profile).then((data) {
          completer.complete('缓存自身的详细信息');
        });
      }
    }

    return completer.future;
  }

  //缓存自身的详细信息
  Future saveProfile(Profile profile) async {
    Completer completer = new Completer();

    SharedPreferences prefs = await SharedPreferences.getInstance();

    Map<String, dynamic> map = profile.toJson();
    map.forEach((key, value) {
      String newKey = 'profile_$key';
      if (value is String) {
//           print('newKey------------$newKey          value------------$value');
        prefs.setString(newKey, value);
      } else {
//        print('newKey-----valueStr-------$newKey          value-------valueStr-----$value');
        String valueStr = value.toString();
        prefs.setString(newKey, valueStr);
      }
    });
    completer.complete('缓存成功');
    return completer.future;
  }

//  deleteAddress async(){
//
//
//  }

  Future beginUpdateAddress() async {
    Completer completer = new Completer();

    String userType = await commonTool.getPreferencesValue('profile_user_type');
//    print('userType------------$userType');
    int userType_Num = int.parse('$userType');
    if (userType_Num == 3) {
      //获取教师通讯录
      tryGetGroupsForTeacher().then((data) {
        completer.complete(data);
      }).catchError((eer) {
        print('error--------tryGetGroupsForTeacher--------------$eer');
        completer.completeError('eer');
      });
    } else {
      //获取家长通讯录
      tryGetGroupsForParent().then((data) {
        completer.complete(data);
      }).catchError((eer) {

        print('error--------tryGetGroupsForParent--------------$eer');
        completer.completeError('eer');
      });
    }

    return  completer.future;
  }

  //获取家长通讯录(清空数据库)
  Future tryGetGroupsForParent() async {
    Completer completer = new Completer();

    String parent_name = await commonTool.getPreferencesValue('profile_name');

    var userProfile_url = await Address.url_get_groupsForParent;
    ResultData res = await HttpManager.getInstance().post(
        userProfile_url,
        {
          'parent_name': '$parent_name',
        },
        responseType: ResponseType.plain);

//    print('res.data-----tryGetGroupsForParent-----------------${res.data}');
    if (res.isSuccess) {
      String str = res.data;
//        print('url_get_RelationAccount--------responseJson--------------$str');
      Map responseJson = jsonDecode(str);

      Map errorMap = responseJson['error'];
      if (errorMap != null && errorMap is Map && errorMap.isNotEmpty == true) {
        String code = errorMap['code'];
        String message = errorMap['message'];

        completer.completeError(message);
        print('error--------tryGetGroupsForParent--------------$message');
      } else {
        commonAddressBook addressBook =
            new commonAddressBook.fromJson(responseJson);
        List groups = addressBook.groups;
//        print('groups-----first------------${groups.first}');

        var isSucceed = await DBManager.shared().deleteAllAddressTable();
        if (isSucceed == true) {
          print('数据库清空成功');
          DBManager.shared().insertGroupsList(groups);

          completer.complete('数据库清空成功');
        } else {
          completer.completeError('数据库清空失败');
          print('数据库清空失败');
        }
      }
    } else {
      String str = res.data;
      Map responseMap = jsonDecode(str);
      Map errorMap = responseMap['error'];
      String code = errorMap['code'];
      String message = errorMap['message'];
      completer.completeError(message);
//       print('error--------tryGetGroupsForParent--------------$message');
    }

    return completer.future;
  }

  //获取教师通讯录(清空数据库)
  Future tryGetGroupsForTeacher() async {
    Completer completer = new Completer();

    Map postMap = await commonTool.getCommonPostForm();

    var userProfile_url = await Address.url_get_groupsForTeacher;
    ResultData res = await HttpManager.getInstance()
        .post(userProfile_url, postMap, responseType: ResponseType.plain);

//    print('res.data-----tryGetGroupsForTeacher-----------------${res.data}');
    if (res.isSuccess) {
      String str = res.data;
//        print('url_get_RelationAccount--------responseJson--------------$str');
      Map responseJson = jsonDecode(str);
      commonAddressBook addressBook =
          new commonAddressBook.fromJson(responseJson);
      List groups = addressBook.groups;
      print('groups-----first------------${groups.first}');

      var isSucceed = await DBManager.shared().deleteAllAddressTable();
      if (isSucceed == true) {
        print('数据库清空成功');
        DBManager.shared().insertGroupsList(groups);
        completer.complete('数据库清空成功');
      } else {
        print('数据库清空失败');
        completer.completeError('数据库清空失败');
      }
    } else {
      String str = res.data;
      Map responseMap = jsonDecode(str);
      Map errorMap = responseMap['error'];
      String code = errorMap['code'];
      String message = errorMap['message'];
      completer.completeError(message);
      print('error--------tryGetGroupsForTeacher--------------$message');
    }

    return completer.future;
  }

  //获取加入群组
  Future tryGetJoinedGroups() async {
    Completer completer = new Completer();

    String user_name = await commonTool.getPreferencesValue('profile_name');

    var userProfile_url = await Address.url_get_joinedGroups;
    ResultData res = await HttpManager.getInstance().post(
        userProfile_url,
        {
          'user_name': '$user_name',
        },
        responseType: ResponseType.plain);

//    print('res.data-----tryGetGroupsForParent-----------------${res.data}');
    if (res.isSuccess) {
      String str = res.data;
//        print('url_get_RelationAccount--------responseJson--------------$str');
      Map responseJson = jsonDecode(str);

      Map errorMap = responseJson['error'];
      if (errorMap != null && errorMap is Map && errorMap.isNotEmpty == true) {
        String code = errorMap['code'];
        String message = errorMap['message'];
        completer.completeError(message);
        print('error--------tryGetJoinedGroups--------------$message');
      } else {
        commonAddressBook addressBook =
            new commonAddressBook.fromJson(responseJson);
        List groups = addressBook.groups;
//        print('groups-----first------------${groups.first}');
        DBManager.shared().insertGroupsList(groups);
        completer.complete('获取加入群组成功');
      }
    } else {
      String str = res.data;
      Map responseMap = jsonDecode(str);
      Map errorMap = responseMap['error'];
      String code = errorMap['code'];
      String message = errorMap['message'];
      completer.completeError(message);
      print('error--------tryGetJoinedGroups--------------$message');
    }

    String userType = await commonTool.getPreferencesValue('profile_user_type');
//    print('userType------------$userType');
    int userType_Num = int.parse('$userType');
    if (userType_Num == 3) {
      completer.future.then((_){tryGetAllUserProfile();});
    }else{
      completer.future.then((_){updateAddressBookSucceed();});
    }

  }

  //获取公共通讯录
  Future tryGetAllUserProfile() async {
    print('tryGetAllUserProfile-------------');
    Completer completer = new Completer();

    Map postMap = await commonTool.getCommonPostForm();

    var userProfile_url = await Address.url_get_getAllUserProfile;
    ResultData res = await HttpManager.getInstance()
        .post(userProfile_url, postMap, responseType: ResponseType.plain);

    print('res.data-----tryGetAllUserProfile-----------------${res.data}');
    if (res.isSuccess) {
      String str = res.data;
//        print('url_get_RelationAccount--------responseJson--------------$str');
      Map responseJson = jsonDecode(str);

      Map errorMap = responseJson['error'];
      if (errorMap != null && errorMap is Map && errorMap.isNotEmpty == true) {
        String code = errorMap['code'];
        String message = errorMap['message'];
        completer.completeError(message);
        print('error--------tryGetAllUserProfile--------------$message');
      } else {
        commonAddressBook addressBook =
            new commonAddressBook.fromJson(responseJson);
        List groups = addressBook.groups;
//        print('groups-----first------------${groups.first}');
        DBManager.shared().insertGroupsList(groups);
        completer.complete('获取公共通讯录成功');
      }
    } else {
      String str = res.data;
      Map responseMap = jsonDecode(str);
      Map errorMap = responseMap['error'];
      String code = errorMap['code'];
      String message = errorMap['message'];
      completer.completeError(message);
      print('error--------tryGetAllUserProfile--------------$message');
    }

    String userType = await commonTool.getPreferencesValue('profile_user_type');
//    print('userType------------$userType');
    int userType_Num = int.parse('$userType');
    if (userType_Num == 3) {
      completer.future.then((_){updateAddressBookSucceed();});
    }


  }

  Future updateAddressBookSucceed() async {
    tryUpdateTheFlagToFalse();
  }

//更改更新标示
  Future tryUpdateTheFlagToFalse() async {
    String user_name = await commonTool.getPreferencesValue('profile_name');
    String user_id = await commonTool.getPreferencesValue('profile_id');

    var userProfile_url = await Address.url_get_updateTheFlagToFalse;
    ResultData res = await HttpManager.getInstance().post(
        userProfile_url,
        {
          'user_name': '$user_name',
          'user_id': '$user_id',
        },
        responseType: ResponseType.plain);

    print('res.data-----tryUpdateTheFlagToFalse-----------------${res.data}');
    if (res.isSuccess) {
      String str = res.data;
//        print('url_get_RelationAccount--------responseJson--------------$str');
      Map responseJson = jsonDecode(str);

      Map errorMap = responseJson['error'];
      if (errorMap != null && errorMap is Map && errorMap.isNotEmpty == true) {
        String code = errorMap['code'];
        String message = errorMap['message'];
        print('error--------tryUpdateTheFlagToFalse--------------$message');
      } else {
        Map statusMap = responseJson['status'];
        String code = statusMap['code'];
        String message = statusMap['message'];
        print('成功--------tryUpdateTheFlagToFalse--------------$message');
      }
    } else {
      String str = res.data;
      Map responseMap = jsonDecode(str);
      Map errorMap = responseMap['error'];
      String code = errorMap['code'];
      String message = errorMap['message'];

      print('error--------tryUpdateTheFlagToFalse--------------$message');
    }
  }
}
